import Vue from 'vue'
import Vuex from 'vuex'
import {request} from '@/common/api/unifun.js'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: '',
		uid:'',
		userInfo: {},
		storeInfo:{}
	},
	getters: {
		hasLogin(state){
			let token  = state.token || uni.getStorageSync('uni_id_token');
			return !!token;
		},
		uid(state){
			return state.uid || uni.getStorageSync('uni_id_uid');
		},
		// 未过期的token
		loginedToken(state){
			if(uni.getStorageSync('uni_id_token_expired') > Date.now()){
				let token;
				if(state.token){
					token = state.token
				}else{
					token = state.token = uni.getStorageSync('uni_id_token');
				}
				return token
			}else{
				return false;
			}
		}
	},
	mutations: {
		//更新state数据
		setStateAttr(state, param){
			if(param instanceof Array){
				for(let item of param){
					state[item.key] = item.val;
				}
			}else{
				state[param.key] = param.val;
			}
		},
		//更新token
		setToken(state, data){
			const {token, tokenExpired} = data;
			state.token = token;
			uni.setStorageSync('uni_id_token', token);
			uni.setStorageSync('uni_id_token_expired', tokenExpired);
			this.dispatch('getUser'); //更新用户信息
		},
		setStoreInfo(state,data){
			state.storeInfo = data
		},
		setUserInfo(state, data){
			state.userInfo = data;
		},
		setUid(state,data){
			state.uid = data;
			uni.setStorageSync('uni_id_uid', data);
		},
		//退出登录
		logout(state){
			state.token = '';
			uni.removeStorageSync('uni_id_token');
			// this.dispatch('getCartCount');//更新购物车数量
			// uni.$emit('refreshCart');//刷新购物车
			// this.dispatch('getOrderCount'); //更新订单数量
			setTimeout(()=>{
				state.userInfo = {};
			}, 1100)
		},
	},
	actions: {
		// 获取用户信息
		getUser({state, commit}){
			return new Promise(async(resolve,reject)=>{
				let userId = state.uid || uni.getStorageSync("uni_id_uid");
				let userInfo;
				if(userId){
					const res = await request('user', 'getById', {
						uid: userId
					});
					if(res.code === 0){
						userInfo = res.userInfo;
						commit('setStateAttr', {
							key: 'userInfo',
							val: userInfo
						})
					}
				}
				resolve(userInfo);
			})
		},
		async getStore({state, commit}){
			const res = await request('store', 'get', {
				_id:state.userInfo.store_id,
				owner:state.userInfo._id
			});
			const {data} = res;
			commit('setStateAttr', {
				key: 'storeInfo',
				val: data
			})
		}
	}
}) 


export default store